package com.neuedu.ec.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.ec.entity.Goods;
import com.neuedu.ec.entity.OrderDitails;
import com.neuedu.ec.entity.Orders;
import com.neuedu.ec.mapper.OrdersMapper;
import com.neuedu.ec.service.IOrderDitailsService;
import com.neuedu.ec.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.ec.vo.GoodsVo;
import com.neuedu.ec.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author 张金山
 * @since 2021-04-12
 */
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    IOrderDitailsService orderDitailsService;

    public static final String CREATE = "1";
    public static final String PAYED = "2";

    @Override
    @Transactional()
    public Orders create(String token, OrderVo orderVo) throws InvocationTargetException, IllegalAccessException {
        String userId = JWT.decode(token).getClaim("openId").asString();
        String nickName = JWT.decode(token).getClaim("nickName").asString();

        // 生成订单号
//        String orderNumber = OrderUtils.getOrderCode(userId);
        String orderNumber = UUID.randomUUID().toString().replace("-", "");

        log.info("创建订单用户id：" + userId);
        log.info("创建订单用户昵称：" + nickName);
        log.info("创建订单orderNumber：" + orderNumber);

        Orders orders = new Orders();
        BeanUtils.copyProperties(orders, orderVo);
        orders.setOrder_number(orderNumber);
        orders.setPay_status(CREATE);
        orders.setUser_id(userId);
        this.save(orders);

        List<GoodsVo> goodVoes = orderVo.getGoods();
        List<OrderDitails> list = new ArrayList();
        OrderDitails orderDitails = null;
        for (GoodsVo goodVo : goodVoes) {
            orderDitails = new OrderDitails();
            BeanUtils.copyProperties(orderDitails, goodVo);
            orderDitails.setOrder_id(orders.getOrder_id());
            list.add(orderDitails);
        }

        orderDitailsService.saveBatch(list);

        return orders;
    }

    @Override
    public Boolean pay(String orderNumber) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_number", orderNumber);
        Orders order = this.getOne(queryWrapper);

        // 设置为已支付状态
        order.setPay_status(PAYED);

        return this.updateById(order);
    }

    @Override
    public List<Orders> all(String token, String type) {
        String userId = JWT.decode(token).getClaim("openId").asString();
        String nickName = JWT.decode(token).getClaim("nickName").asString();

        log.info(String.format("查询订单列表,openId：%s\t微信昵称:%s,type:%s", userId, nickName, type));

//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("user_id",userId);
//        if("1".equals(type)){
//            queryWrapper.eq("pay_status",CREATE);
//        }else if ("2".equals(type)){
//            queryWrapper.eq("pay_status",CREATE);
//        }
        List<Orders> ordersList = getBaseMapper().all(userId, type);


        for (Orders orders : ordersList) {
            List<Goods> goods = orders.getGoods();
            double total_price = 0.0;
            for (Goods good : goods) {
                total_price += good.getGoods_total_price().doubleValue();
            }
            orders.setTotal_count(goods.size());
            orders.setTotal_price(total_price);
        }

        return ordersList;
    }
}
